<?php

namespace app\api\controller;

use app\common\model\ExpressTrace;
use app\admin\model\Order;
use app\api\service\Message as MessageService;
use think\Exception;
use think\Log;

//    {
//        "RequestData": {
//        "PushTime": "2019-01-28 09:49:07",
//		"EBusinessID": "1345426",
//		"Data": [{
//            "LogisticCode": "75126776956302",
//			"ShipperCode": "ZTO",
//			"Traces": [{
//                "AcceptStation": "【哈尔滨市】  【黑龙江市场部】（0451-87933335、18946171625） 的 李先生 （15504610462） 已揽收",
//				"AcceptTime": "2019-01-25 16:26:44"
//			}, {
//                "AcceptStation": "【哈尔滨市】  快件离开 【黑龙江市场部】 已发往 【哈尔滨中转】",
//				"AcceptTime": "2019-01-25 16:28:43"
//			}, {
//                "AcceptStation": "【哈尔滨市】  快件已经到达 【哈尔滨中转】",
//				"AcceptTime": "2019-01-25 22:34:49"
//			}, {
//                "AcceptStation": "【哈尔滨市】  快件离开 【哈尔滨中转】 已发往 【武汉中转部】",
//				"AcceptTime": "2019-01-25 22:35:04"
//			}, {
//                "AcceptStation": "【武汉市】  快件已经到达 【武汉中转部】",
//				"AcceptTime": "2019-01-27 17:58:59"
//			}, {
//                "AcceptStation": "【武汉市】  快件离开 【武汉中转部】 已发往 【武昌】",
//				"AcceptTime": "2019-01-27 18:38:04"
//			}, {
//                "AcceptStation": "【武汉市】  快件已经到达 【武昌】",
//				"AcceptTime": "2019-01-28 06:41:24"
//			}, {
//                "AcceptStation": "[武汉市][武昌](027-88415771、027-88415747)的(徐梅芳)正在派件(13545278900)请保持电话畅通，并耐心等待",
//				"AcceptTime": "2019-01-28 09:47:43"
//			}],
//			"State": "2",
//			"EBusinessID": "1345426",
//			"Success": true
//		}],
//		"Count": "1"
//	},
//	"DataSign": "ODRiZGMxNWM5ZDcxM2RkOTkyNGUyOGNhNTc2NGQ1MDU=",
//	"RequestType": "101"
//}
class KuaiDiNiaoNotify
{
    public function index(){
        $data = file_get_contents('php://input');
        $msg  = explode("&", $data);
        foreach ($msg as $k => $v) {
            $p = explode("=", $v);
            if ($p[0] == "RequestData") {
                $result[$p[0]] = json_decode(urldecode($p[1]),true);
            } else {
                $result[$p[0]] = urldecode($p[1]);
            }
        }
        $res = $this->traceUpdate($result['RequestData']['Data']);
        echo '{
                "EBusinessID": "'.$result['RequestData']['EBusinessID'].'",
                "UpdateTime": "'. date('Y-m-d H:i:s', time()) .'",
                "Success": "'. $res['status'] .'",
                "Reason": "'. $res['err_msg'] .'"
            }';
    }

    private function traceUpdate($result){
        try {
            $model = new ExpressTrace();
            foreach ($result as $v){
                $ExpressTrace = ExpressTrace::where('express_no',$v['LogisticCode'])->find();
                if($ExpressTrace){
                    $ExpressTrace->state = $v['State'];
                    $ExpressTrace->traces = json_encode($v['Traces']);
                    $ExpressTrace->save();
                }else{
                    $model->express_no = $v['LogisticCode'];
                    $model->shipper_code = $v['ShipperCode'];
                    $model->state = $v['State'];
                    $model->traces = json_encode($v['Traces']);
                    $model->save();
                }
            }

            $res['status'] = true;
            $res['err_msg'] = '';


            $model = new \app\admin\model\Member();
            $where = [
                'm_status' => 1
            ];
            $field = 'id, c_id';
            // 所有用户
            $memberIds = $model->where($where)->field($field)->select();
            if($memberIds) {
                foreach ($memberIds as $item) {
                    $memberId = $item['id'];
                    // 查看物流信息，是否有更新
                    $orders = Order::where(['member_id' => $memberId, 'status' => 3])->field('id, express_no')->select();
                    if ($orders) {
                        $messLogisticsDB = db('message_logistics');
                        foreach ($orders as $order) {
                            // 物流接口 查看物流信息
                            $expressTrace = ExpressTrace::where(['express_no' => $order['express_no']])->find();
                            if ($expressTrace) {
                                $traces = json_decode($expressTrace['traces'], true);
                                foreach ($traces as $trace) {
                                    // 是否存在旧的物流消息
                                    $logisticsMes = $messLogisticsDB->where(['member_id' => $memberId, 'express_no' => $order['express_no'], 'create_date' => $trace['AcceptTime']])->find();
                                    if ($logisticsMes) {
                                        continue;
                                    }
                                    // 添加物流消息 -- 只添加最新的物流消息
                                    $logisticsData = [
                                        //'create_date' => date('Y-m-d H:i:s'),
                                        'create_date' => $trace['AcceptTime'],
                                        'member_id' => $memberId,
                                        //'order_id' => $order['id'],
                                        'express_no' => $order['express_no'],
                                        'title' => $trace['AcceptStation'],
                                        'detail' => $trace['AcceptStation'],
                                    ];
                                    $logisticsMesRes = $messLogisticsDB->insert($logisticsData);

                                    // 推送送APP消息
                                    $mesData = [
                                        'template_type' => 1,
                                        'template_data' => [
                                            'transmission_type' => 1,
                                            'transmission_content' => '',
                                            'title' => $trace['AcceptStation'],
                                            'text' => $trace['AcceptStation'],
                                            'logo'  => '',
                                            'logo_url'  => '',
                                        ],
                                        'cid' => $item['c_id'], // 推送通知至指定用户时填写
                                        'cid_list' => '', // 推送通知至指定用户列表时填写
                                    ];
                                    MessageService::pushLogistics($mesData);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception $e) {
            Log::record($e,'error');
        }
    }
}